from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from seo.models import Keyword, Group, GroupKeyword, GroupCategory
from seo.services import getCategoryNameById, getCategoryIdByName, createMETA, getCategoriesByGroup


def view(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        return render_to_response('seo/view.html', {'keywords': Keyword.objects.all(), 'groups': Group.objects.all()},
                                  context_instance=RequestContext(request))
    return HttpResponseRedirect(reverse('home'))


def updateMETA(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        createMETA()
        return HttpResponseRedirect(reverse('seo_home'))
    return HttpResponseRedirect(reverse('home'))


def addKeyword(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.method == 'POST':
            if request.POST.has_key('word'):
                Keyword.objects.get_or_create(word=request.POST['word'])
        return HttpResponseRedirect(reverse('seo_home'))
    return HttpResponseRedirect(reverse('home'))


def deletekeyword(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.method == 'GET':
            if request.GET.has_key('id'):
                Keyword.objects.filter(id=request.GET['id']).delete()
        return HttpResponseRedirect(reverse('seo_home'))
    return HttpResponseRedirect(reverse('home'))


def addGroup(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.method == 'POST':
            if request.POST.has_key('group') and request.POST.has_key('category'):
                group = Group.objects.get_or_create(name=request.POST['group'])[0]
                group.category = request.POST['category']
                if request.POST.has_key('word'):
                    word = Keyword.objects.get_or_create(request.POST['word'])[0]
                    group.keywords = word
                group.save()
        return HttpResponseRedirect(reverse('seo_home'))
    return HttpResponseRedirect(reverse('home'))


def deleteGroup(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.method == 'GET':
            if request.GET.has_key('id'):
                Group.objects.filter(id=request.GET['id']).delete()
        return HttpResponseRedirect(reverse('seo_home'))
    return HttpResponseRedirect(reverse('home'))


def groupView(request, groupId):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        group = Group.objects.get_or_create(id=groupId)[0]

        if group:
            if request.method == "POST":
                if request.POST.has_key('key'):
                    if request.POST['key']:
                        GroupKeyword.objects.get_or_create(group=group, word=request.POST['key'])
                if request.POST.has_key('cat'):
                    cat = request.POST['cat']
                    if cat.isdigit():
                        if getCategoryNameById(cat):
                            GroupCategory.objects.get_or_create(group=group, category=cat)
                    else:
                        cat = getCategoryIdByName(cat)
                        if cat:
                            GroupCategory.objects.get_or_create(group=group, category=cat)
            elif request.GET:
                try:
                    if request.GET.has_key('delkey'):
                        GroupKeyword.objects.filter(group=group, word=request.GET['delkey']).delete()
                    if request.GET.has_key('delcat'):
                        GroupCategory.objects.filter(group=group, category=request.GET['delcat']).delete()
                    return HttpResponseRedirect('/seo/group/%s' % groupId)
                except ValueError, MultiValueDictKeyError:
                    pass
            keywords = GroupKeyword.objects.filter(group=group)
            categories = getCategoriesByGroup(group)
            group.save()
            return render_to_response('group.html', {'group': group, 'categories': categories, 'keywords': keywords},
                                      context_instance=RequestContext(request))
        return HttpResponseRedirect(reverse('seo_home'))
    return HttpResponseRedirect(reverse('home'))